package com.example.stream.create;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * @author: wyb
 * @date: 2021/11/2 9:42
 * @describe: 创建流的方式
 * @vision 1.0
 */
public class CreateStream {

    public static void main(String[] args) {
        // 1、使用Collection下的 stream() 和 parallelStream() 方法
        ArrayList<Object> list = new ArrayList<>();
        Stream<Object> stream = list.stream();//顺序流
        Stream<Object> objectStream = list.parallelStream();//并行流

        // 2、使用Arrays 中的 stream() 方法，将数组转成流
        Integer[] nums = new Integer[6];
        Stream<Integer> stream1 = Arrays.stream(nums);

        // 3、使用Stream中的静态方法：of()、iterate()、generate()
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4);
        Stream<Integer> iterate = Stream.iterate(1, x -> x * 2).limit(5);
        iterate.forEach(System.out::println);
        Stream<Double> generate = Stream.generate(Math::random).limit(5);
        generate.forEach(System.out::println);

        // 4、使用 BufferedReader.lines() 方法，将每行内容转成流
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("D:\\study-project\\ship\\stream\\src\\main\\java\\com\\example\\stream\\create\\test_stream.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Stream<String> lineStream = reader.lines();
        lineStream.forEach(System.out::println);

        // 5、使用 Pattern.splitAsStream() 方法，将字符串分隔成流
        Pattern pattern = Pattern.compile(",");
        Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");
        stringStream.forEach(System.out::println);

    }
}
